import axios from "axios";
import http from 'http'
import https from 'https';
import qs from 'qs'

const defaults = {
    headers: {
        post: {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
        },
        'X-Requested-With': 'XMLHttpRequest'
    },
    baseURL: 'http://127.0.0.1:3000/api',
    timeout:1000*3,
    // 跨域是否带Token
    withCredentials: true,
    responseType: 'json',
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    // 用于node.js
    httpAgent: new http.Agent({
        keepAlive: true
    }),
    httpsAgent: new https.Agent({
        keepAlive: true
    })
}
if (process.server) {
    defaults.baseURL = `http://${process.env.HOST || 'localhost'}:${process.env.PORT || 3000}/api`
}
const service = axios.create(defaults)
// POST 传参序列化
service.interceptors.request.use(
  config => {
    //if (config.method === 'post') config.data = qs.stringify(config.data)
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 返回状态判断
service.interceptors.response.use(
  res => {
    return res.data
  },
  error => {
    return Promise.reject(error)
  }
)

export default service;